<template>
  <div>
    <van-search placeholder="请输入要搜索的商品" shape="round" @click="$router.push('/m/goods/search')"/>

    <div class="cate">
      <van-sidebar v-model="activeKey" @change="changeSide">
        <van-sidebar-item
          :title="item.name"
          v-for="item in topCates"
          :key="item.id"
        />
      </van-sidebar>

      <div class="right-cate">
        <div
          class="right-cate-item"
          v-for="(item, index) in subCategory"
          :key="index"
        >
          <van-image :src="item.icon">
            <template v-slot:error>加载失败</template>
          </van-image>
          <p>{{ item.name }}</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "",
  data() {
    return {
      activeKey: 0,
      url: "",
      topCates: [{ name: "所有分类", id: 0 }], //顶级分类
      allCates: [], //二级分类
    };
  },
  mounted() {
    this.url = this.$store.state.mobile.yxUrl;
    this.getCates();
  },
  methods: {
    //获取分类的信息
    getCates() {
      this.$axios.post(`${this.url}/shop/goods/category/all`).then((res) => {
        console.log(res);
        //筛选出顶级分类
        let tmp_arr = res.data.filter((item) => {
          return item.pid == 0;
        });
        //把顶级分类添加到topCates
        this.topCates.push(...tmp_arr);

        //把所有的分类subCates
        this.allCates = res.data; //所有分类
      });
    },

    //点击左侧菜单切换
    changeSide(index) {
      console.log(this.activeKey, index);
      console.log(this.topCates[index]);
    },
  },
  computed: {
    //获取右侧二级分类
    subCategory() {
      let arr = this.allCates; //转中间变量

      if (this.activeKey == 0) {
        //所有分类
        console.log(arr);
        return arr;
      } else {
        //点击其他顶级分类
        let pid = this.topCates[this.activeKey].id;
        console.log(pid);
        return arr.filter((item) => {
          return item.pid == pid;
        });
      }
    },
  },
  watch: {},
};
</script>

<style lang="scss" scoped>
.cate {
  width: 100%;
  display: flex;
  justify-content: space-between;
  .van-sidebar {
    width: 25%;
  }
  .right-cate {
    width: 70%;
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    .right-cate-item {
      width: 31%;
      margin: 2% 1%;
      box-sizing: border-box;
      img {
        width: 90%;
      }
      p {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }
}
</style>